package classload;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author ZhengDp
 * @Date 2023/5/14 23:42
 */
public class ClassLoad_Demo3 {
    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader classLoader = new MyClassLoader();
        classLoader.loadClass("MapImpl1");
    }
}


class MyClassLoader extends ClassLoader {
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 文件真实路径
        String path = "" + name + ".class";
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 将二进制字节信息放到 os中
        try {
            Files.copy(Paths.get(path), os);
            byte[] bytes = os.toByteArray();
            // byte[] --> *.class
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException("类文件未找到", e);
        }
    }
}
